#! /usr/bin/env python
#coding=utf-8
#******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# Author: senlin
# Create: 2020-08-10
# ******************************************************************************/

import logging
import os.path
import time


class Logger():

     #日志级别的字典
    level_relations = {"debug": logging.DEBUG, 
                        "info": logging.INFO, 
                        "warning": logging.WARNING,
                        "error": logging.ERROR, 
                        "critical": logging.CRITICAL}

    #fmtStr = "[%(asctime)s] - %(levelname)s - %(name)s - %(filename)s[line:%(lineno)d] - %(message)s"
            
    ########
    # Specify the file path, log level, and call file to save the log
    ########
    def __init__(self, module, clevel = logging.DEBUG, flevel = logging.DEBUG):
        #self.name = module
        #self.formatter = fmtStr
        currentTime=time.strftime('%Y%m%d%H%M', time.localtime(time.time()))  # return current time
        currentPath=os.path.dirname(os.getcwd())  # return current path
        logPath=currentPath + '/Logs/'

        dirTime = time.strftime('%Y%m%d', time.localtime(time.time()))
        isExists=os.path.exists(logPath + dirTime)
        if not isExists:
            os.makedirs(logPath + dirTime)
            print(logPath + dirTime + " make dir success!")
        else:
            print(logPath + "dir: %s exist!" % dirTime)

        try:
            # init logger 
            # getLogger()方法后面最好加上所要日志记录的模块名字，
            # 后面的日志格式中的%(name)s 对应的是这里的模块名字
            self.log = logging.getLogger(module)
            self.log.setLevel(logging.DEBUG)

            # Define the path and name of the log file
            logName = logPath  + dirTime + '/' + currentTime + '.log'  
            self.log.logName = logName
            # Create a handler to write to the log file
            fh = logging.FileHandler(logName)
            fh.setLevel(flevel)

            # Create a handler to output to the console
            ch = logging.StreamHandler()
            ch.setLevel(clevel)

            # Define the output format of the handler
            formatter = logging.Formatter('[%(asctime)s] - %(levelname)s - %(name)s -  %(funcName)s[line:%(lineno)d] - %(message)s')

            fh.setFormatter(formatter)
            ch.setFormatter(formatter)

            # Add handler to logger
            self.log.addHandler(fh)
            self.log.addHandler(ch)
            
        except Exception as e:
            print("Failed to output log！ %s" % e)

    def getlog(self):
        return self.log
    # 日志接口，用户只需调用这里的接口即可，这里只定位了INFO, WARNING, ERROR三个级别的日志，可根据需要定义更多接口


if __name__ == '__main__':

    testlog = Logger('TestMode').getlog()
    testlog.info("This is info: %s %s", "sen", "lin")
    testlog.warning('This is warning')
    testlog.error('This is error')